<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('cou_courseschedule_template')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl"
                @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <!-- 高级查询区域 -->
      <j-super-query :fieldList="superFieldList" ref="superQueryModal"
                     @handleSuperQuery="handleSuperQuery"></j-super-query>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete" />
            删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
      <template>
        <span style="float:right;">
          <a @click="searchQuery()"><a-icon type="sync" />刷新</a>
          <a-divider type="vertical" />
          <a-button v-print="'#datatable'" ghost type="primary">打印</a-button>
        </span>
      </template>
    </div>

    <!-- table区域-begin -->
    <a-table
      size="middle"
      :scroll="{x:true}"
      bordered
      :columns="columns"
      :data-source="dataSource"
      :expandedRowKeys="expandedRowKeys"
      @expand="fatherExpand"
      :pagination="ipagination"
      ref="table"
      class="components-table-demo-nested"
      :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
      :rowKey="record=>record.id"
      @change="handleTableChange">
      <a-table
        size="small"
        slot="expandedRowRender"
        :rowKey="record.id"
        slot-scope="record"
        :columns="innerColumns"
        :data-source="innerData"
        :pagination="false"
        class="components-table-demo-nested"
        bordered
      >
       <span slot="action" slot-scope="text, record">
         <a @click="addAtom()">新增</a>
         <a-divider type="vertical" />
         <a @click="editAtom(record)">编辑</a>
         <a-divider type="vertical" />
         <a @click="handleDelete(record)">删除</a>
       </span>
      </a-table>
      <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
        <a-divider type="vertical" />
         <a @click="handleDelete(record.id)">删除</a>
        <a-divider type="vertical" />
         <a @click="distributionClick(record.id)">下发</a>
        </span>
    </a-table>

    <cou-courseschedule-template-modal ref="modalForm" @ok="modalFormOk"></cou-courseschedule-template-modal>

    <div>
      <a-modal
        title="编辑"
        :visible="visible"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="序号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="courTempAtomSection">
              <a-input-number :min="1" v-model="editModel.courTempAtomSection" style="width: 40%"/>

            </a-form-model-item>
            <a-form-model-item label="节次名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="courTempAtomSectionName">
              <a-input v-model="editModel.courTempAtomSectionName" placeholder="例如：第二节" style="width: 48%"/>
              <!--              <j-dict-select-tag type="list" v-model="editModel.courTempAtomSectionName" dictCode="cour_sche_atom_section_name"-->
              <!--                                 placeholder="节次名称" />-->
            </a-form-model-item>
          </a-col>

          </a-row>
        <a-row>
          <a-col :xl='24' :lg='7' :md='10' :sm='24'>
            <a-form-model-item label="上课时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="courTempAtomStartTime">
              <j-time placeholder="请选择上课时间" v-model="editModel.courTempAtomStartTime" style="width: 48%" />
              <label>-</label>
              <j-time placeholder="下课时间" v-model="editModel.courTempAtomEndTime" style="width: 48%" />
            </a-form-model-item>

          </a-col>
<!--          <a-col :span="12">-->
<!--            <a-form-model-item label="下课时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="courTempAtomEndTime">-->
<!--              <j-time placeholder="请选择下课时间" v-model="editModel.courTempAtomEndTime" style="width: 100%" />-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="星期一 " :labelCol="labelCol" :wrapperCol="wrapperCol" prop="courTempAtomMonday">
              <j-dict-select-tag type="list" v-model="editModel.courTempAtomMonday" dictCode="cour_sch_tem_auto_flag"
                                 placeholder="请选择上课时间或内容" style="width: 48%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="周期二 " :labelCol="labelCol" :wrapperCol="wrapperCol"
                               prop="courTempAtomTuesday">
              <j-dict-select-tag type="list" v-model="editModel.courTempAtomTuesday" dictCode="cour_sch_tem_auto_flag"
                                 placeholder="请选择上课时间或内容 " style="width: 48%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="星期三 " :labelCol="labelCol" :wrapperCol="wrapperCol"
                               prop="courTempAtomWednesday">
              <j-dict-select-tag type="list" v-model="editModel.courTempAtomWednesday" dictCode="cour_sch_tem_auto_flag"
                                 placeholder="请选择上课时间或内容 "  style="width: 48%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="星期四 " :labelCol="labelCol" :wrapperCol="wrapperCol"
                               prop="courTempAtomThursday">
              <j-dict-select-tag type="list" v-model="editModel.courTempAtomThursday" dictCode="cour_sch_tem_auto_flag"
                                 placeholder="请选择上课时间或内容 " style="width: 48%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="星期五 " :labelCol="labelCol" :wrapperCol="wrapperCol" prop="courTempAtomFriday">
              <j-dict-select-tag type="list" v-model="editModel.courTempAtomFriday" dictCode="cour_sch_tem_auto_flag"
                                 placeholder="请选择上课时间或内容 " style="width: 48%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="星期六 " :labelCol="labelCol" :wrapperCol="wrapperCol"
                               prop="courTempAtomSaturday">
              <j-dict-select-tag type="list" v-model="editModel.courTempAtomSaturday" dictCode="cour_sch_tem_auto_flag"
                                 placeholder="请选择上课时间或内容 " style="width: 48%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="星期日 " :labelCol="labelCol" :wrapperCol="wrapperCol" prop="courTempAtomSunday">
              <j-dict-select-tag type="list" v-model="editModel.courTempAtomSunday" dictCode="cour_sch_tem_auto_flag"
                                 placeholder="请选择上课时间或内容 " style="width: 48%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="特殊标识" :labelCol="labelCol" :wrapperCol="wrapperCol"
                               prop="courTempAtomSpecialFlag">
              <a-input-number v-model="editModel.courTempAtomSpecialFlag" placeholder="默认为空" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-modal>
    </div>

    <div>
      <a-modal
        title="Title"
        :visible="distributionVisible"
        @ok="handleDistribution"
        @cancel="distributionVisible = false"
      >
        <a-row>
          <!--          <a-col :span="24">-->
          <!--            <a-form-model-item label="课表模板" :labelCol="labelCol" :wrapperCol="wrapperCol"-->
          <!--                               prop="coursescheduleTemplateId">-->
          <!--              <a-select v-model="model.coursescheduleTemplateId" placeholder="请选择应用模板"-->
          <!--                        defaultValue="1"-->
          <!--                        :getPopupContainer="(target) => target.parentNode" style="width: 50%;">-->
          <!--                <a-select-option v-for="item in templateList" :key="item.value">{{ item.label }}</a-select-option>-->
          <!--              </a-select>-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <a-col :span="24">
            <a-form-model-item label="关联对象类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="relObjTtype">
              <j-dict-select-tag @change="handleChangeObjType" type="list" v-model="model.relObjTtype"
                                 style="width: 50%;"
                                 dictCode="course_target_obj_ttype" placeholder="请选择关联对象类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="目标对象" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="relObjId">
              <a-select v-model="model.relObjId" placeholder="请输入目标对象" mode="multiple" :allowClear="true"
                        :getPopupContainer="(target) => target.parentNode" style="width: 50%;">
                <a-select-option v-for="item in objectList" :key="item.value">{{ item.label }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-modal>

    </div>
  </a-card>
</template>

<script>

import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import { getAction, putAction, postAction } from '@api/manage'
import CouCoursescheduleTemplateModal from './modules/CouCoursescheduleTemplateModal'
import {
  getAllClass,
  getClassroomDataList,
  getClassStudentQueryAll,
  getSubjectList,
  getTeacherList
} from '@api/commonAPI'

export default {
  name: 'couCourseScheduleManage',
  mixins: [JeecgListMixin, mixinDevice],
  components: { CouCoursescheduleTemplateModal },
  data() {
    return {
      description: 'cou_courseschedule_template管理页面',
      visible: false,
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '模板编码',
          align: 'center',
          dataIndex: 'courscheTempNo'
        },
        {
          title: '模板名称',
          align: 'center',
          dataIndex: 'courscheTempName'
        },
        {
          title: '课表模板类型',
          align: 'center',
          dataIndex: 'courscheTempTtype_dictText'
        },
        {
          title: '课表状态',
          align: 'center',
          dataIndex: 'courscheTempStatus_dictText'
        },
        {
          title: '特殊标识',
          align: 'center',
          dataIndex: 'courscheTempSpecialFlag_dictText'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/cou_courseschedule_template/couCoursescheduleTemplate/list',
        delete: '/cou_courseschedule_template/couCoursescheduleTemplate/delete',
        deleteBatch: '/cou_courseschedule_template/couCoursescheduleTemplate/deleteBatch',
        exportXlsUrl: '/cou_courseschedule_template/couCoursescheduleTemplate/exportXls',
        importExcelUrl: 'cou_courseschedule_template/couCoursescheduleTemplate/importExcel',
        addAtomUrl: '/courschetemplateatom/couCourScheTemplateAtom/add',
        editAtomUrl: '/courschetemplateatom/couCourScheTemplateAtom/edit'

      },
      editModel: {},
      dictOptions: {},
      superFieldList: [],
      expandedRowKeys: [],
      innerColumns: [
        // {
        //   title: '#',
        //   dataIndex: '',
        //   key: 'rowIndex',
        //   width: 60,
        //   align: 'center',
        //   customRender: function(t, r, index) {
        //     return parseInt(index) + 1
        //   }
        // },
        {
          title: '序号',
          align: 'center',
          dataIndex: 'courTempAtomSection',
          // sorter: true,
          defaultSortOrder: 'descend',
          width: 30,
          sorter: (a, b) => b.courTempAtomSection - a.courTempAtomSection
        },
        {
          title: '节次名称',
          align: 'center',
          dataIndex: 'courTempAtomSectionName',
          // sorter: true,
          defaultSortOrder: 'descend',
          width: 100,
        },
        {
          title: '上课时间',
          align: 'center',
          width: 100,
          dataIndex: 'courTempAtomStartTime'
        },
        {
          title: '下课时间',
          align: 'center',
          width: 100,
          dataIndex: 'courTempAtomEndTime'
        },
        {
          title: '星期一 ',
          align: 'center',
          dataIndex: 'courTempAtomMonday_dictText'
        },
        {
          title: '周期二 ',
          align: 'center',
          dataIndex: 'courTempAtomTuesday_dictText'
        },
        {
          title: '星期三 ',
          align: 'center',
          dataIndex: 'courTempAtomWednesday_dictText'
        },
        {
          title: '星期四 ',
          align: 'center',
          dataIndex: 'courTempAtomThursday_dictText'
        },
        {
          title: '星期五 ',
          align: 'center',
          dataIndex: 'courTempAtomFriday_dictText'
        },
        {
          title: '星期六 ',
          align: 'center',
          dataIndex: 'courTempAtomSaturday_dictText'
        },
        {
          title: '星期日 ',
          align: 'center',
          dataIndex: 'courTempAtomSunday_dictText'
        },
        // {
        //   title: '特殊标识',
        //   align: 'center',
        //   dataIndex: 'courTempAtomSpecialFlag'
        // },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 100,
          scopedSlots: { customRender: 'action' }
        }
      ],
      innerData: [],
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      distributionVisible: false,
      model: {},
      validatorRules: {
        courTempAppIzSingle: [
          { required: true, message: '请输入单双周标识(1单周，2双周)!' }
        ]
      },
      objectList: [],
      templateList: []
    }
  },
  created() {
    this.getSuperFieldList()
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  methods: {
    initDictConfig() {
    },
    handleCancel() {
      this.visible = false
    },
    editAtom(record) {
      this.visible = true
      this.editModel = record
    },
    addAtom() {
      this.visible = true
      this.editModel = {}
    },
    handleOk() {
      if (this.editModel.id != null) {
        putAction(this.url.editAtomUrl, this.editModel).then(res => {
          if (res.success) {
            this.$message.success('编辑成功')
            this.visible = false
          } else {
            this.$message.error('编辑失败')
          }
        })
      } else {
        postAction(this.url.addAtomUrl, this.editModel).then(res => {
          if (res.success) {
            this.$message.success('添加成功')
            this.visible = false
          } else {
            this.$message.error('添加失败')
          }
        })
      }

    },
    distributionClick(id) {
      this.distributionVisible = true
      this.model.coursescheduleTemplateId = id
    },
    handleDistribution() {
      let model = this.model
      let params = {
        coursescheduleTemplateId: model.coursescheduleTemplateId,
        relObjId: JSON.stringify(model.relObjId),
        relObjTtype: model.relObjTtype
      }
      postAction('/relcourschetempapp/relCourScheTempApp/addBatch', params).then(res => {
        if (res.success) {
          this.distributionVisible = false
          this.$message.success('下发成功')
          this.model = {}
        } else {
          this.$message.error('下发失败')
        }
      })
    },
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'courscheTempNo', text: '模板编码', dictCode: '' })
      fieldList.push({ type: 'string', value: 'courscheTempName', text: '模板名称', dictCode: '' })
      fieldList.push({
        type: 'int',
        value: 'courscheTempTtype',
        text: '课表模板类型（0全校通用课表 1:班级(需分配);2教室场地 3.老师;4.科目 5:学生）',
        dictCode: 'coursche_temp_ttype'
      })
      fieldList.push({
        type: 'int',
        value: 'courscheTempStatus',
        text: '课表状态（1编辑 2发布待应用 3应用中  4下线不用 ）',
        dictCode: 'coursche_temp_status'
      })
      fieldList.push({ type: 'int', value: 'courscheTempSpecialFlag', text: '特殊标识', dictCode: '' })
      this.superFieldList = fieldList
    },
    fatherExpand(expanded, record) {
      if (expanded) {
        this.expandedRowKeys.push(record.id)
        this.getChildTable(record)
      } else {
        this.expandedRowKeys.splice(this.expandedRowKeys.indexOf(record.id), 1)
      }
    },
    async getChildTable(record) {
      let params = {
        templateId: record.id
      }
      //queryTemplateAtomByTempId params
      getAction('/courschetemplateatom/couCourScheTemplateAtom/queryTemplateAtomByTempId',params).then(res => {
        if (res.success) {
          this.innerData = res.result.records
          // console.log(res.result)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    handleChangeObjType() {
      let type = this.model.relObjTtype
      this.objectList = []
      switch (type) {
        case '1':
          this.getClassesList()
          break
        case '2' :
          this.getClassroomList()
          break
        case '3':
          this.getTeacherList()
          break
        case '4':
          this.getSubjectList()
          break
        case '5':
          this.getStudentList()
          break
        default :
          this.$message.error('获取初始化数组出错')
      }
    },
    async getClassesList() {
      let res = await getAllClass()
      if (res.success) {
        res.result.forEach(item => {
          this.objectList.push({
            label: item.className,
            value: item.id
          })
        })
      } else {
        this.$message.error('获取初始化数组出错')
      }
    },
    async getClassroomList() {
      let res = await getClassroomDataList()
      if (res.success) {
        res.result.forEach(item => {
          this.objectList.push({
            label: item.classroomName,
            value: item.id
          })
        })
      } else {
        this.$message.error('获取初始化数组出错')
      }
    },
    async getTeacherList() {
      let res = await getTeacherList()
      if (res.success) {
        res.result.forEach(item => {
          this.objectList.push({
            label: item.teacherName,
            value: item.teacherId
          })
        })
      } else {
        this.$message.error('获取初始化数组出错')
      }
    },
    async getSubjectList() {
      let res = await getSubjectList()
      if (res.success) {
        res.result.forEach(item => {
          this.objectList.push({
            label: item.subjectName,
            value: item.subjectId
          })
        })
      } else {
        this.$message.error('获取初始化数组出错')
      }
    },
    async getStudentList() {
      let res = await getClassStudentQueryAll()
      if (res.success) {
        res.result.forEach(item => {
          this.objectList.push({
            label: item.studentName,
            value: item.id
          })
        })
      } else {
        this.$message.error('获取初始化数组出错')
      }
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>